package com.chang.soul.conf;

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 跨域等相关操作
 * @author xiaoqingyang@vip.henu.edu.cn
 * @date 2021/3/24 21:48
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {

	}

	/**
	 * 设置最大上传文件大小
	 *
	 * @return
	 */
	@Bean
	public MultipartConfigElement multipartConfigElement() {
		MultipartConfigFactory factory = new MultipartConfigFactory();
		// 文件最大KB,MB
		factory.setMaxFileSize("10240MB");
		// 设置总上传数据总大小
		factory.setMaxRequestSize("10240MB");
		return factory.createMultipartConfig();

	}

	@Override
	public void configurePathMatch(PathMatchConfigurer configurer) {
		super.configurePathMatch(configurer);
		configurer.setUseSuffixPatternMatch(true);// 当此参数设置为true的时候，那么/user.html，/user.aa，/user.*都能是正常访问的。
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {

		registry.addInterceptor(new JwtInterceptor()).addPathPatterns("/**")
				// 需要排除的路径设置
				.excludePathPatterns("/page/**", "/swagger-ui.html/**", "/login/**", "/configuration/*", "/v2/api-docs",
						"/swagger-resources");

	}

	/**
	 * 跨域问题的处理
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**").allowedOrigins("*")

				.allowedHeaders("Cache-Control", "no-cache").allowCredentials(true)
				.allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD")
				.allowedHeaders("Access-Control-Allow-Origin", "*").maxAge(3600 * 24);

	}

}
